import 'whatwg-fetch'
import { HTTP_URL } from './http_url_config'
export default ({ url, app, method = 'post', body = '', loading = false }) => {
  return new Promise(async (resolve, reject) => {
    // 判断loading
    if (loading) {
      app.$store.commit('showLoading')
    }
    // 增加配置
    let config = {
      method,
      headers: {
        'Content-Type': 'application/json',
        'token': app.$base.getSessionStorage('token')
      }
    }
    if (method !== 'get') {
      config = {
        ...config,
        body
      }
    }
    // 发送请求
    try {
      // let response = await window.fetch(`/standard${url}`, config)
      let fetchUrl = process.env.NODE_ENV === 'development' ? `/batterycar${url}` : `${HTTP_URL}/batterycar${url}`
      let response = await window.fetch(fetchUrl, config)
      if (response.status !== 200) {
        throw (response.statusText)
      }
      let data = await response.json()
      if (loading) {
        app.$store.commit('hideLoading')
      }
      if (data.code === 0) {
        // 获取数据
        resolve(data)
      } else {
        if (data.code === 403) {
          if (!app.$store.state.loginShow) {
            app.$alert('登录信息失效，请重新登录', '警告', {
              confirmButtonText: '确定',
              callback: () => {
                app.$router.replace({ name: 'index' })
              }
            })
          }
          app.$store.commit('changeLoginShow', true)
          app.$base.setSessionStorage('token', '')
        } else {
          reject(data.msg)
        }
      }
    } catch (error) {
      // 报错
      if (loading) {
        app.$store.commit('hideLoading')
      }
      reject(error)
    }
  })
}
